package main

import (
	"flag"
	"fmt"
	"net"
	"strconv"
)

//Port 端口
var Port string

func main() {

	fmt.Println("process start...")
	flag.StringVar(&Port, "p", "", "proc port")
	flag.Parse()
	if Port == "" {
		fmt.Print("port is null\n")
		return
	}

	p, err := strconv.Atoi(Port)

	if err != nil {
		fmt.Printf("port is not number and err:[%v]\n", err)
		return
	}

	addr := fmt.Sprintf("0.0.0.0:%d", p)
	listener, err := net.Listen("tcp", addr)
	if err != nil {
		fmt.Printf("err! addr %s open faild err:[%v]\n", addr, err)
		return
	}

	for {

		conn, err := listener.Accept()
		if err != nil {
			fmt.Printf("listen err:[%v]\n", err)
		}

		go handConn(conn)
	}

}

func handConn(conn net.Conn) {
	defer func() {
		fmt.Printf("client [%s] close\n", conn.RemoteAddr().String())
		conn.Close()
	}()
	var buf [1024]byte
	for {
		n, err := conn.Read(buf[:])
		if err != nil {
			fmt.Printf("read from %s msg faild err:[%v]\n", conn.RemoteAddr().String(), err)
			break
		}
		fmt.Printf("rev data from %s msg:%s\n", conn.RemoteAddr().String(), string(buf[:n]))
	}

}
